﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TakePhotoTogether.Communication.Protocols
{
    /// <summary>
    /// Represents a payload of packets addressed to send/receive image bytes
    /// </summary>
    public class ImageData : PayloadData
    {
        /// <summary> Width of image </summary>
        public int width;
        /// <summary> Height of image </summary>
        public int height;
        /// <summary> byte array of image </summary>
        public byte[] data;

        /// <summary>
        /// Constructor to create a payload using image attributes
        /// </summary>
        /// <param name="imageBytes"></param>
        /// <param name="imageWidth"></param>
        /// <param name="imageHeight"></param>
        public ImageData(byte[] imageBytes, int imageWidth, int imageHeight)
        {
            width = imageWidth;
            height = imageHeight;
            data = imageBytes;
        }

        /// <summary>
        /// Constructor to get image data from payload bytes
        /// </summary>
        /// <param name="packetData"></param>
        public ImageData(byte[] packetData)
        {
            ParseFromBytes(packetData, 0);
        }

        /// <summary>
        /// Parse byte to extract field information
        /// </summary>
        /// <param name="packetData"></param>
        /// <param name="startPos"></param>
        protected void ParseFromBytes(byte[] packetData, int startPos)
        {
            if (packetData != null)
            {
                int dataSize = packetData.Length - 8 - startPos;
                data = new byte[dataSize];

                width = BitConverter.ToInt32(packetData, startPos);
                height = BitConverter.ToInt32(packetData, startPos + 4);

                for (int i = 0; i < dataSize; i++)
                {
                    data[i] = packetData[i + 8 + startPos];
                }
            }
        }

        /// <summary>
        /// Get byte array representation of payload
        /// </summary>
        /// <returns></returns>
        public virtual byte[] ToBytes()
        {
            byte[] payloadData = new byte[data.Length + 8];

            byte[] widthBytes = BitConverter.GetBytes(width);
            byte[] heightBytes = BitConverter.GetBytes(height);

            for (int i = 0; i < 4; i++)
            {
                payloadData[i] = widthBytes[i];
                payloadData[i+4] = heightBytes[i];
            }

            for (int i = 0; i < data.Length; i++)
            {
                payloadData[i + 8] = data[i];
            }

            return payloadData;
        }
    }
}
